package com.elinkway.infinitemovies.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

import com.elinkway.infinitemovies.config.SettingManage;
import com.elinkway.infinitemovies.http.api.MoviesHttpApi;
import com.elinkway.infinitemovies.utils.BitmapUtils;
import com.elinkway.infinitemovies.utils.ImageUploadUtil;
import com.elinkway.infinitemovies.utils.ToastUtil;
import com.le123.ysdq.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;

@SuppressLint("NewApi")
public class CropUserPortraitActivity extends BaseActivity implements ImageUploadUtil.OnUploadProcessListener{
	private static final String TAG="CropThumbnailActivity";
	private final int RE_SELECT_PICTURE = 105;
	private final int RE_TAKE_PICTURE = 106;
	/** 图片类型 */
	private final String IMAGE_TYPE = "image/*";
	/** 手势状态常量-无 */
	private static final int NONE = 0;
	/** 手势状态常量-拖拽 */
	private static final int DRAG = 1;
	/** 手势状态常量-缩放 */
	private static final int ZOOM = 2;
	/** 屏幕宽度 */
	private int mScreenWidth;
	/** 图片地址 */
	private String pic;
	/** 图片宽度 */
	private float picWith;
	/** 图片高度 */
	private float picHeight;
	/** 图片根据屏幕缩放后的比例，保证图片最短边填充屏幕 */
	private float picMinScale = 1.0f;

	private LinearLayout mReSelectPictureLayout;
	/** 重拍按钮 */
	private LinearLayout mReTakePictureLayout;
	/** 预览图片 */
	private ImageView mImageView;
	/** 缩略图缓存 */
	private Bitmap mBitmap;
	/** 显示可缩放及裁剪框的布局 */
	private RelativeLayout mPictureViewLayout;
	/** 裁剪框屏幕边距 */
	private int mCropMargin;
	/** 图片缩放参数 */
	private Matrix matrix = new Matrix();
	/** 上一次图片缩放参数 */
	private Matrix savedMatrix = new Matrix();
	/** 手势状态 */
	private int mode = NONE;
	/** 手指开始触摸时对应的屏幕点 */
	private PointF start = new PointF();
	/** 缩放时两指中间屏幕点 */
	private PointF mid = new PointF();
	/** 上一次缩放比例 */
	private float oldDist = 1f;
	private SharedPreferences mLoginSp;

	public static final int NETTYPE_NO = 0;
	public static final int NETTYPE_WIFI = 1;
	public static final int NETTYPE_2G = 2;
	public static final int NETTYPE_3G = 3;
	public static final int NETTYPE_4G = 4;

	public final static String NEWIMGURL = "newimgurl";

	private boolean isUploading = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 设置应用窗体模式为全屏模式
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.crop_portrait);
		findViews();
		// 获取屏幕宽度
		WindowManager wm = this.getWindowManager();
		mScreenWidth = wm.getDefaultDisplay().getWidth();
		// 获取裁剪框屏幕边距，20dp是和layout对应的
		mCropMargin = dipToPx(20);

		// 设置封面预览图宽高
		LayoutParams para = (LayoutParams) mPictureViewLayout.getLayoutParams();
		para.height = mScreenWidth;
		para.width = mScreenWidth;
		mPictureViewLayout.setLayoutParams(para);

		mReSelectPictureLayout.setOnClickListener(new ButtonOnClickListener());
		mReTakePictureLayout.setOnClickListener(new ButtonOnClickListener());
		mImageView.setOnTouchListener(new ImageOnTouchListener());
		// 从Intent中获取缩略图文件路径
		pic = getIntent().getStringExtra("thumbnail");

		if (TextUtils.isEmpty(pic)) {
			ToastUtil.showShortToast(CropUserPortraitActivity.this, "图片选择失败");
			CropUserPortraitActivity.this.finish();
		}

		if (pic != null && !"".equals(pic)) {
			//图像打开时适当的软缩放
			mBitmap = BitmapUtils.decodeFile(pic);
			if(mBitmap == null) {
				finish();
				return;
			}
			//判断是否需要旋转图片
			int degree=BitmapUtils.readPictureDegree(pic);
			if(degree!=0){
				mBitmap=BitmapUtils.rotaingImageView(degree, mBitmap);
			}

			//设置封面大图
			mImageView.setImageBitmap(mBitmap);
			// 获取图片宽高
			picWith = mBitmap.getWidth();
			picHeight = mBitmap.getHeight();
			//获得图片最短边缩放至屏幕宽度的比例
			if (picWith < picHeight) {
				picMinScale = (float) mScreenWidth / picWith;
			} else {
				picMinScale = (float) mScreenWidth / picHeight;
			}
			//缩放封面大图到上面获得的比例
			matrix = mImageView.getImageMatrix();
			matrix.postScale(picMinScale, picMinScale);
			mImageView.setImageMatrix(matrix);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	private void findViews() {
		mLoginSp = getSharedPreferences(SettingManage.LOGIN_INFO, Context.MODE_PRIVATE);
		mImageView = (ImageView) findViewById(R.id.picture);
		// 设置状态条透明
		mImageView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
		mReSelectPictureLayout = (LinearLayout) findViewById(R.id.re_select_picture_layout);
		mReTakePictureLayout = (LinearLayout) findViewById(R.id.re_take_picture_layout);
		mPictureViewLayout = (RelativeLayout) findViewById(R.id.picture_view);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// 此处的 RESULT_OK是系统自定义得一个常量
		if (resultCode == RESULT_OK) {
			if (requestCode == RE_SELECT_PICTURE) {
				Uri selectedImage = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				Cursor cursor = getContentResolver().query(selectedImage,
						filePathColumn, null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String picturePath = cursor.getString(columnIndex);
				cursor.close();
				// 拷贝文件到相应目录下

				copyFile(picturePath, pic);

				if (pic != null && !"".equals(pic)) {
	            	mImageView.setImageMatrix(null);
	            	matrix=new Matrix();
	    			//图像打开时适当的软缩放
	    			mBitmap = BitmapUtils.decodeFile(pic);
	    			//判断是否需要旋转图片
					int degree=BitmapUtils.readPictureDegree(pic);
					if(degree!=0){
						mBitmap=BitmapUtils.rotaingImageView(degree, mBitmap);
					}
	    			//设置封面大图
	    			mImageView.setImageBitmap(mBitmap);
	    			// 获取图片宽高
	    			picWith = mBitmap.getWidth();
	    			picHeight = mBitmap.getHeight();
	    			//获得图片最短边缩放至屏幕宽度的比例
	    			if (picWith < picHeight) {
	    				picMinScale = (float) mScreenWidth / picWith;
	    			} else {
	    				picMinScale = (float) mScreenWidth / picHeight;
	    			}
	    			//缩放封面大图到上面获得的比例
	    			matrix = mImageView.getImageMatrix();
	    			matrix.postScale(picMinScale, picMinScale);
	    			mImageView.setImageMatrix(matrix);
	    		}
			} else if (requestCode == RE_TAKE_PICTURE) {
				if (pic != null && !"".equals(pic)) {
					mImageView.setImageMatrix(null);
	            	matrix=new Matrix();
					//图像打开时适当的软缩放
					mBitmap = BitmapUtils.decodeFile(pic);

					//判断是否需要旋转图片
					int degree=BitmapUtils.readPictureDegree(pic);
					if(degree!=0){
						mBitmap=BitmapUtils.rotaingImageView(degree, mBitmap);
					}

					//设置封面大图
					mImageView.setImageBitmap(mBitmap);
					// 获取图片宽高
					picWith = mBitmap.getWidth();
					picHeight = mBitmap.getHeight();
					//获得图片最短边缩放至屏幕宽度的比例
					if (picWith < picHeight) {
						picMinScale = (float) mScreenWidth / picWith;
					} else {
						picMinScale = (float) mScreenWidth / picHeight;
					}
					//缩放封面大图到上面获得的比例
//					Matrix mt = mImageView.getImageMatrix();
//					mt.postScale(picMinScale, picMinScale);
//					mImageView.setImageMatrix(mt);
					matrix = mImageView.getImageMatrix();
	    			matrix.postScale(picMinScale, picMinScale);
	    			mImageView.setImageMatrix(matrix);
				} else {
					ToastUtil.showShortToast(CropUserPortraitActivity.this, "图片选择失败");
					CropUserPortraitActivity.this.finish();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onUploadDone(int responseCode, String message) {
//		ToastUtil.showShortToast(this, "头像上传成功");
		String imgUrl = "";
		String code = "";
		String msg = "";
		try {
			JSONObject result = new JSONObject(message);
			if(result != null){
				code = result.optString("code");
				if (result.optJSONObject("data") != null) {
					imgUrl = result.optJSONObject("data").optString("url");
				}
				msg = result.optString("msg");
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}

		Intent intent = new Intent();
		intent.putExtra(NEWIMGURL, imgUrl);
		intent.putExtra("code", code);
		intent.putExtra("msg", msg);
		setResult(RESULT_OK, intent);
		if(!"1".equals(ImageUploadUtil.UPLOAD_SUCCESS_CODE)){
			isUploading = false;
		}
		finish();
	}

	@Override
	public void onUploadProcess(int uploadSize) {
//		ToastUtil.showShortToast(this, "头像上传中");
	}

	@Override
	public void initUpload(int fileSize) {

	}

	private class ButtonOnClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.re_select_picture_layout:// 返回
				finish();
				break;
			case R.id.re_take_picture_layout:// 裁剪

				/** TODO 裁剪后需要统计及上传图片，先检测网络状态 */
//				int netType = HttpUtils.getNetType(CropUserPortraitActivity.this);
//				if (netType == NETTYPE_NO) {
//					ToastUtil.showMessage(getApplicationContext(),
//							R.string.nonetwork);
//					return;
//				}
//				startProgressDialog();
				if(!isUploading){
					isUploading = true;
					new Refresh().execute();
				}
				break;
			default:
				break;
			}
		}

	}

	protected class Refresh extends AsyncTask<Void, Void, Void> {
		private String fileName;
		private File file;

		@Override
		protected Void doInBackground(Void... params) {
			//获取图片左上角点left和top,及图片当前缩放比例
			float[] matrixValues = new float[9];
			matrix.getValues(matrixValues);
			float left = matrixValues[2];
			float top = matrixValues[5];
			float scale=matrixValues[0];
			//计算出裁剪框内的图片坐标及宽高
			int x=(int) ((mCropMargin-left)/scale);
			int y=(int) ((mCropMargin-top)/scale);
			int w=(int) ((mScreenWidth - mCropMargin*2)/scale);
			int h=(int) ((mScreenWidth - mCropMargin*2)/scale);
			// 进行图片裁剪
			Bitmap mBitmap2 = Bitmap.createBitmap(mBitmap, x, y, w, h);
			// 图片压缩
			mBitmap2 = BitmapUtils.compressImage(mBitmap2, 40);
			// 保存图片
			BitmapUtils.savePic(mBitmap2, pic, CompressFormat.PNG);
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			Map<String, String> param = new HashMap<>();
			param.put("suffix", "png");
			param.put("uid", mLoginSp.getString(LoginActivity.UID, ""));
			ImageUploadUtil.getInstance().setOnUploadProcessListener(CropUserPortraitActivity.this);
			ImageUploadUtil.getInstance().uploadFile(pic, mLoginSp.getString(LoginActivity.TOKEN, ""), MoviesHttpApi.getStaticHead() + "kuaikan/apiimgupload_json.so?apiversion=2", param );

		}
	}

	/**
	 * 图片缩放时手指Touch事件
	 */
	private class ImageOnTouchListener implements OnTouchListener {
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			switch (event.getActionMasked()) {
			case MotionEvent.ACTION_DOWN://单指按下
				//临时保存上一次图片缩放参数
				matrix.set(mImageView.getImageMatrix());
				savedMatrix.set(matrix);
				//临时保存开始时手指所在屏幕点
				start.set(event.getX(), event.getY());
				//设置当前模式为拖拽
				mode = DRAG;
//				DebugLog.log(TAG, "--->>matrix:"+matrix.toString());
				break;
			case MotionEvent.ACTION_UP://单指抬起
				if (mode == DRAG) {
					//获取最新的图片缩放参数
					float[] matrixValues = new float[9];
					matrix.getValues(matrixValues);
//					DebugLog.log("CropThumbnail", "--->>:" + matrix.toString());
					float left = matrixValues[2];
					float top = matrixValues[5];
					float right = left + picWith * matrixValues[0];
					float bottom = top + picHeight * matrixValues[4];
					// 计算各边边距
					float leftDis = left;
					float rightDis = mScreenWidth - right;
					float topDis = top;
					float bottomDis = mScreenWidth - bottom;
					//如果图片某边缩放到裁剪框范围内时，自动将图片该边与裁剪框该边对齐，类似于一种磁性吸引的效果，保证裁剪框没有空白背景
					if (left > mCropMargin) {
						matrixValues[2] = mCropMargin;
					}
					if (top > mCropMargin) {
						matrixValues[5] = mCropMargin;
					}
					if (right < mScreenWidth - mCropMargin && leftDis < rightDis) {
						matrixValues[2] = left + (mScreenWidth - mCropMargin - right);
					}
					if (bottom < mScreenWidth - mCropMargin && topDis < bottomDis) {
						matrixValues[5] = top + (mScreenWidth - mCropMargin - bottom);
					}
					//设置计算后的缩放参数
					matrix.setValues(matrixValues);
					//设置当前模式为无
					mode = NONE;
//					DebugLog.log(TAG, "--->>matrix:"+matrix.toString());
				}
				break;
			case MotionEvent.ACTION_POINTER_DOWN: // 多点触摸按下
				//计算缩放的距离
				oldDist = spacing(event);
				if (oldDist > 10.0f) {
					savedMatrix.set(matrix);
					//计算手指缩放时的中心点，并缓存
					midPoint(mid, event);
					//设置当前模式为缩放
					mode = ZOOM;
				}
				break;
			case MotionEvent.ACTION_POINTER_UP://多点触摸抬起
				//设置当前模式为无
				mode = NONE;
				//获取最新的图片缩放参数
				float[] matrixValues1 = new float[9];
				matrix.getValues(matrixValues1);
//				DebugLog.log("CropThumbnail", "--->>:" + matrix.toString());
				float left = matrixValues1[2];
				float top = matrixValues1[5];
				float right = left + picWith * matrixValues1[0];
				float bottom = top + picHeight * matrixValues1[4];
				float currentScale = matrixValues1[0];
				//计算图片适合裁剪框的最小比例
				float fixScale = picMinScale * (1.0f - (float) mCropMargin * 2 / mScreenWidth);
				// 计算各边边距
				float leftDis = left;
				float rightDis = mScreenWidth - right;
				float topDis = top;
				float bottomDis = mScreenWidth - bottom;

				if (currentScale < fixScale) {//当前缩放比例小于图片适合裁剪框的最小比例
					//设置缩放比例为图片适合裁剪框的最小比例
					matrixValues1[0] = fixScale;
					matrixValues1[4] = fixScale;
					//如果图片某边缩放到裁剪框范围内时，自动将图片该边与裁剪框该边对齐，类似于一种磁性吸引的效果，保证裁剪框没有空白背景
					if (left > mCropMargin) {
						matrixValues1[2] = mCropMargin;
					}
					if (top > mCropMargin) {
						matrixValues1[5] = mCropMargin;
					}
					if (right < mScreenWidth - mCropMargin && leftDis < rightDis) {
						right = left + picWith * fixScale;
						matrixValues1[2] = left + (mScreenWidth - mCropMargin - right);
					}
					if (bottom < mScreenWidth - mCropMargin && topDis < bottomDis) {
						bottom = top + picHeight * fixScale;
						matrixValues1[5] = top + (mScreenWidth - mCropMargin - bottom);
					}
					//设置计算后的缩放参数
					matrix.setValues(matrixValues1);
				} else {
					//当前缩放比例大于图片适合裁剪框的最小比例
					if (currentScale < fixScale*5) {//当前缩放比例小于图片适合裁剪框的最小比例5倍
						if (left > mCropMargin) {
							matrixValues1[2] = mCropMargin;
						}
						if (top > mCropMargin) {
							matrixValues1[5] = mCropMargin;
						}
						if (right < mScreenWidth - mCropMargin && leftDis < rightDis) {
							matrixValues1[2] = left + (mScreenWidth - mCropMargin - right);
						}
						if (bottom < mScreenWidth - mCropMargin && topDis < bottomDis) {
							matrixValues1[5] = top + (mScreenWidth - mCropMargin - bottom);
						}
						matrix.setValues(matrixValues1);
					}else{
						//设置缩放比例为图片适合裁剪框的最小比例5倍、缩放中心位置
						matrix.postScale(fixScale*5/matrixValues1[0], fixScale*5/matrixValues1[0], mid.x, mid.y);
					}
				}
				break;
			case MotionEvent.ACTION_MOVE:
				if (mode == DRAG) { // 图片拖动
					matrix.set(savedMatrix);
					matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
//					DebugLog.log(TAG, "--->>matrix:"+matrix.toString());
				} else if (mode == ZOOM) {// 图片缩放
					//计算缩放的距离
					float newDist = spacing(event);
					if (newDist > 10.0f) {
						matrix.set(savedMatrix);
						//计算缩放比例
						float scale = newDist / oldDist;
						matrix.postScale(scale, scale, mid.x, mid.y);
					}
				}
				break;
			}

			mImageView.setImageBitmap(mBitmap);
			mImageView.setImageMatrix(matrix);
			return true;
		}

	}

	/**
	 * 计算缩放时手指滑动距离
	 */
	private float spacing(MotionEvent event) {
		float x = event.getX(0) - event.getX(1);
		float y = event.getY(0) - event.getY(1);
		return (float) Math.sqrt(x * x + y * y);
	}

	/**
	 * 计算缩放时两手指中心点
	 */
	private void midPoint(PointF point, MotionEvent event) {
		float x = event.getX(0) + event.getX(1);
		float y = event.getY(0) + event.getY(1);
		point.set(x / 2, y / 2);
	}

	private int dipToPx(int dipValue) {
		final float scale = getResources()
				.getDisplayMetrics().density;
		int pxValue = (int) (dipValue * scale + 0.5f);

		return pxValue;
	}

	public static void copyFile(String oldPath, String newPath) {
		try {
			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			if (oldfile.exists()) { // 文件存在时
				FileReader inStream = new FileReader(oldfile); // 读入原文件
				FileWriter fs = new FileWriter(newPath);
				char[] buffer = new char[1024];
				while ((byteread = inStream.read(buffer)) != -1) {
					bytesum += byteread; // 字节数 文件大小
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
			}
		} catch (Exception e) {
			// System.out.println("复制单个文件操作出错");
			e.printStackTrace();
		}
	}

}